package com.zou.recruit.controller;

import com.zou.recruit.mapper.UserMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @author: 邹祥发
 * @date: 2021/9/27 20:33
 */
@Controller
public class editPwdController {

    @Resource
    private UserMapper userMapper;

    //修改用户密码页（跳转页面）
    @RequestMapping(value = "/pwd", method = RequestMethod.GET)
    public String editPassword() {
        return "user/pwd";
    }

    //修改密码方法（更新数据）
    @RequestMapping(value = "/editPwd", method = RequestMethod.POST)
    public String editPwd(@RequestParam("primaryPwd") String primaryPwd,
                          @RequestParam("newPwd") String newPwd,
                          @RequestParam("reNewPwd") String reNewPwd,
                          HttpSession session, Model model,
                          SessionStatus sessionStatus) {
        //通过session获取登录的用户名
        String name = (String) session.getAttribute("user");
        //根据用户名查找该用户的密码
        String password = userMapper.selectPwdByName(name);
        //用户输入的原密码与数据库密码一致
        if (primaryPwd.equals(password)) {
            //用户输入的新密码与原密码不相同
            if (!primaryPwd.equals(newPwd)) {
                //用户两次输入的新密码一致
                if (newPwd.equals(reNewPwd)) {
                    //通过用户名修改密码
                    userMapper.editPwd(newPwd, name);
                    //清除session
                    session.invalidate();
                    sessionStatus.setComplete();

                    return "user/login";
                } else {
                    //两次输入的密码不一致
                    model.addAttribute("msg", "两次输入的新密码不一致！");
                }
            } else {
                //新密码与原密码相同
                model.addAttribute("msg", "新密码不能与原密码相同！");
            }
        } else {
            //用户输入的原密码错误
            model.addAttribute("msg", "原密码错误！");
        }

        return "user/pwd";
    }
}
